package com.example.goodpet.activity.Fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.example.goodpet.R;
import com.example.goodpet.activity.SearchActivity;
import com.example.goodpet.base.BaseFragment;
import com.example.goodpet.bean.BannerInfoDTO;
import com.example.goodpet.bean.ChannelInfoDTO;
import com.example.goodpet.bean.MainChannel;
import com.example.goodpet.bean.ResponseBody;
import com.example.goodpet.bean.UserPetInfo;
import com.example.goodpet.common.EndlessRecyclerOnScrollListener;
import com.example.goodpet.common.LoadMoreWrapper;
import com.example.goodpet.home.homeRecommend.adapter.HomeRecommendFragmentAdapter;
import com.example.goodpet.home.homeRecommend.adapter.RecommendRecycleViewAdapter;
import com.example.goodpet.home.homeRecommend.adapter.viewholder.BannerViewHolder;
import com.example.goodpet.home.homeRecommend.adapter.viewholder.ChannelViewHolder;
import com.example.goodpet.home.homeRecommend.adapter.viewholder.MainChannelViewHolder;
import com.example.goodpet.home.homeRecommend.bean.Species;
import com.example.goodpet.service.HomeService;
import com.example.goodpet.utils.Constants;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.RetrofitSingleton;
import com.example.goodpet.utils.TimeSeed;
import com.example.goodpet.utils.UIUtils;
import com.github.gzuliyujiang.dialog.DialogColor;
import com.github.gzuliyujiang.dialog.DialogConfig;
import com.github.gzuliyujiang.dialog.DialogStyle;
import com.github.gzuliyujiang.wheelpicker.AddressPicker;
import com.github.gzuliyujiang.wheelpicker.OptionPicker;
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode;
import com.github.gzuliyujiang.wheelpicker.contract.OnAddressPickedListener;
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener;
import com.github.gzuliyujiang.wheelpicker.entity.CityEntity;
import com.github.gzuliyujiang.wheelpicker.entity.CountyEntity;
import com.github.gzuliyujiang.wheelpicker.entity.ProvinceEntity;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainChannelFragment extends BaseFragment {
    private String TAG=this.getClass().getSimpleName();

    private Retrofit retrofit;
    private HomeService homeService;
    //VLayout
    private VirtualLayoutManager layoutManager;
    //主页上方适配器集合
    private List<DelegateAdapter.Adapter> subAdapters = new LinkedList();
    //宠物信息适配器集合
    private List<DelegateAdapter.Adapter> subAdaptersPet = new LinkedList();
    //宠物信息列表集合，访问服务器获取
    private static List<UserPetInfo> userPetInfos = new ArrayList<>();
    //用来获取布局
    private LayoutInflater mLayoutInflater;

    //用来保存页面信息
    private MainChannel.ResultDTO resultDTO;

    private RecyclerView rvParent;
    private RecyclerView rvPet;
    //筛选列表的2个按钮
    private TextView tv_screening_location;
    private TextView tv_screening_search;

    //speciesId 默认为0  0在数据库表示查询任意种类的宠物
    private int speciesId=0;
    //location默认为tv_screening_location外显文本
    private String location="地区";
    private long seed= TimeSeed.Get();

    @Override
    public View initView() {
        View view = View.inflate(mContext, R.layout.fragment_main_channel, null);
        tv_screening_search=view.findViewById(R.id.tv_screening_search);
        tv_screening_location=view.findViewById(R.id.tv_screening_location);
        rvParent=view.findViewById(R.id.rv_parent);
        rvPet=view.findViewById(R.id.rv_pet);
        mLayoutInflater = LayoutInflater.from(mContext);

        //如果定位失败，则提示相应的信息
        if(MyApplication.location == ""){
            UIUtils.toast("定位失败",false);

        }else{
            //定位成功，location修改成相应的定位，tv_screening_location外显文本也发生相应改变
            location=MyApplication.location;
        }
        tv_screening_location.setText(location);
        //初始化监听
        initListener();

        return view;
    }


    /**
     * 初始化页面数据（接受从activity传来的页面数据）
     */
    @Override
    public void initData() {
        super.initData();
        Bundle arguments = getArguments();
        ArrayList<ChannelInfoDTO> channelInfo = arguments.getParcelableArrayList("channelInfo");
        ArrayList<BannerInfoDTO> bannerInfo = arguments.getParcelableArrayList("bannerInfo");
        int petId = arguments.getInt("petId");
        speciesId=petId;
        resultDTO=new MainChannel.ResultDTO();
        resultDTO.setChannelInfo(channelInfo);
        resultDTO.setBannerInfo(bannerInfo);


        if(!channelInfo.isEmpty() && !bannerInfo.isEmpty()){
            //有数据
            //初始化主页上方的页面
            initVLayoutRvParent();
            //根据location和species初始化宠物信息数据
            initPetData();
        }else{
            UIUtils.toast("未获取到页面信息",false);
        }

    }

    /**
     * 根据用户点击的按钮，初始化pet宠物信息
     */
    private void initPetData() {
        retrofit = RetrofitSingleton.getRetrofitConstance();
        homeService = retrofit.create(HomeService.class);

        // 3 表示该页面为其他宠物的页面
        if(speciesId==3){
            homeService.selectMainChannelUserPetInfo(seed,location,1)
                    .enqueue(new Callback<ResponseBody<List<UserPetInfo>>>() {
                        @Override
                        public void onResponse(Call<ResponseBody<List<UserPetInfo>>> call, Response<ResponseBody<List<UserPetInfo>>> response) {
                            ResponseBody<List<UserPetInfo>> body = response.body();
                            if(body.getCode()==200){
                                userPetInfos = body.getData();
//                            Log.e(TAG, "onResponse: "+pets);
                            }else{
                                userPetInfos=null;
                                UIUtils.toast("未获取到宠物信息！",false);
                            }
                            initVLayoutRvPet();
                        }

                        @Override
                        public void onFailure(Call<ResponseBody<List<UserPetInfo>>> call, Throwable t) {
//                            Log.e(TAG, "onFailure: "+t );
                            UIUtils.toast("网络通信失败",false);
                        }
                    });
        }else if(speciesId==1 || speciesId==2){
            // 1 2分别表示流浪猫和流浪狗 使用selectSpecificPetInfo方法， 1 2在数据库中分别也表示查询流浪狗和流浪猫
            homeService
                    .selectSpecificUserPetInfo(seed,location,speciesId,1)
                    .enqueue(new Callback<ResponseBody<List<UserPetInfo>>>() {
                        @Override
                        public void onResponse(Call<ResponseBody<List<UserPetInfo>>> call, Response<ResponseBody<List<UserPetInfo>>> response) {
                            ResponseBody<List<UserPetInfo>> body = response.body();
                            if (body.getCode() == 200) {
                                userPetInfos = body.getData();
//                          Log.e(TAG, "onResponse: "+pets);
                            } else {
                                userPetInfos = null;
                                UIUtils.toast("未获取到宠物信息！", false);
                            }
                            initVLayoutRvPet();
                        }

                        @Override
                        public void onFailure(Call<ResponseBody<List<UserPetInfo>>> call, Throwable t) {
                            UIUtils.toast("网络通信失败",false);
                        };

           });
        }
    }

    /**
     * 初始化宠物信息adapter
     */
    private void initVLayoutRvPet() {
        //1.设置总布局管理器
        layoutManager = new VirtualLayoutManager(mContext);
        rvPet.setLayoutManager(layoutManager);
        //2.设置回收池大小（相同类型的View可以复用，防止多次创建ItemView）
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 10);
        rvPet.setRecycledViewPool(viewPool);
        //3.逐个设置子模块适配器
        subAdaptersPet.clear();
        addPetAdapter();

        //4.设置总适配器
        DelegateAdapter mainAdapter = new DelegateAdapter(layoutManager, true);
        mainAdapter.setAdapters(subAdaptersPet);
        rvPet.setAdapter(mainAdapter);
    }
    /**
     * 添加宠物信息的适配器到展示宠物信息的页面
     */
    private void addPetAdapter() {
        GridLayoutHelper layoutHelper = new GridLayoutHelper(2);
        RecommendRecycleViewAdapter adapter = new RecommendRecycleViewAdapter(mContext, userPetInfos);
        LoadMoreWrapper loadMoreWrapper = new LoadMoreWrapper(adapter){
            @Override
            public LayoutHelper onCreateLayoutHelper() {
                return layoutHelper;
            }
        };
//        rvParent.setAdapter(loadMoreWrapper);
        subAdaptersPet.add(loadMoreWrapper);


        rvPet.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING);
                homeService.selectSpecificUserPetInfo(seed,location, speciesId, ++loadMoreWrapper.page)
                        .enqueue(new Callback<ResponseBody<List<UserPetInfo>>>() {
                            @Override
                            public void onResponse(Call<ResponseBody<List<UserPetInfo>>> call, Response<ResponseBody<List<UserPetInfo>>> response) {
                                ResponseBody<List<UserPetInfo>> body1 = response.body();
//                        int code=body1.getCode();
//                        Log.e(TAG, "onResponse: "+code );
                                if (body1.getCode()==200){
                                    List<UserPetInfo> data1 = body1.getData();
//                                    Log.e(TAG, "onResponse: "+data1);
                                    userPetInfos.addAll(data1);
                                    loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_COMPLETE);
                                }else if (body1.getCode()==404){
                                    loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_END);
                                }

                            }

                            @Override
                            public void onFailure(Call<ResponseBody<List<UserPetInfo>>> call, Throwable t) {
                                UIUtils.toast("连接服务器失败",false);
                            }
                        });
            }
        });
    }

    /**
     * 初始化页面信息adapter
     */
    private void initVLayoutRvParent() {
        //1.设置总布局管理器
        layoutManager = new VirtualLayoutManager(mContext);
        rvParent.setLayoutManager(layoutManager);
        //2.设置回收池大小（相同类型的View可以复用，防止多次创建ItemView）
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 10);
        rvParent.setRecycledViewPool(viewPool);
        //3.逐个设置子模块适配器
        addChannelAdapter();
        addBannerAdapter();

        //4.设置总适配器
        DelegateAdapter mainAdapter = new DelegateAdapter(layoutManager, true);
        mainAdapter.setAdapters(subAdapters);
        rvParent.setAdapter(mainAdapter);
    }

    /**
     * 添加轮播图的适配器到主页上方的页面
     */
    private void addBannerAdapter() {
        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(1);
        HomeRecommendFragmentAdapter adapter = new HomeRecommendFragmentAdapter(){
            @Override
            public LayoutHelper onCreateLayoutHelper() {
                return gridLayoutHelper;
            }

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                return new BannerViewHolder(mContext, mLayoutInflater.inflate(R.layout.banner_viewpager, null));
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                BannerViewHolder bannerViewHolder = (BannerViewHolder) holder;
                bannerViewHolder.setData(resultDTO.getBannerInfo());
            }
        };
        subAdapters.add(adapter);
    }

    /**
     * 添加图标的适配器到主页上方的页面
     */
    private void addChannelAdapter() {
        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(5);
        gridLayoutHelper.setBgColor(Color.WHITE);
        HomeRecommendFragmentAdapter adapter = new HomeRecommendFragmentAdapter(){
            @Override
            public LayoutHelper onCreateLayoutHelper() {
                return gridLayoutHelper;
            }

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                return new ChannelViewHolder(mContext,mLayoutInflater.inflate(R.layout.channel_item,null));
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                ChannelViewHolder channelViewHolder = (ChannelViewHolder) holder;
                channelViewHolder.setData(resultDTO.getChannelInfo());
            }
        };
        subAdapters.add(adapter);

    }

    /**
     * 初始化监听
     */
    private void initListener() {

        tv_screening_location.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            DialogConfig.setDialogStyle(DialogStyle.Three);
            DialogConfig.setDialogColor(new DialogColor()
                    .cancelTextColor(0xFF999999)
                    .okTextColor(0xFF0099CC));

            AddressPicker picker = new AddressPicker(getActivity());
            picker.setAddressMode(AddressMode.PROVINCE_CITY);

            picker.setOnAddressPickedListener(new OnAddressPickedListener() {
                @Override
                public void onAddressPicked(ProvinceEntity province, CityEntity city, CountyEntity county) {
                    /**
                     * 监测到地区改变，外显按钮文本进行相应的改变后，根据用户选择重新初始化对应的宠物信息
                     */
                    if(null!=city){
                        tv_screening_location.setText(city.getName());
                    }else{
                        tv_screening_location.setText(province.getName());
                    }
                    location=tv_screening_location.getText().toString();
//                        UIUtils.toast(location,false);
                    initPetData();
                }
            });
            picker.show();
        }
    });

        tv_screening_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                UIUtils.toast("搜索",false);
                Intent intent=new Intent(mContext, SearchActivity.class);
                intent.putExtra("type",1);
                mContext.startActivity(intent);
            }

        });
    }
}
